
import wx
import wx.gizmos

class PluginMixin(object):
    """Base plugin class.

    Used for storing cross-plugin functionality.

    User-changable fields:
        name -- config name (one that is shown on notebook tab).
        _wxGuiDataMethods -- dict that defines getter/setter methods
            for given GUI objects.
    """

    _app = _config = None
    name = "PleaseOverride"
    _configGuiMap = ()
    _wxGuiDataMethods = {
        wx.CheckBox: ("Get3StateValue", "Set3StateValue"),
        wx.DirPickerCtrl: ("GetPath", "SetPath"),
        wx.gizmos.EditableListBox: ("GetStrings", "SetStrings"),
        wx.TextCtrl: ("GetValue", "SetValue"),
    }

    def _mixinInit(self, formParent, app):
        """Must be called by parent upon init."""
        self._app = app
        self._config = app.readPluginConfig(self.name)

    def configDefaultVal(self, name, value):
        """If config part `name` does not exist, set it to given value."""
        if name not in self._config:
            self._config[name] = value

    def setControls(self):
        """Set GUI controls to a values from config."""
        for (_control, _name) in self._configGuiMap:
            (_getter, _setter) = self._findMethods(_control)
            _setter(self._config[_name])

    def getControls(self):
        """Set values in config to a data form GUI controls."""
        for (_control, _name) in self._configGuiMap:
            (_getter, _setter) = self._findMethods(_control)
            self._config[_name] = _getter()

    def _findMethods(self, obj):
        """Find and return getter/setter methods for given wx class."""
        for (_cls, (_getter, _setter)) in self._wxGuiDataMethods.iteritems():
            if isinstance(obj, _cls):
                _getMeth = getattr(obj, _getter)
                _setMeth = getattr(obj, _setter)
                return (_getMeth, _setMeth)
        raise Exception("Methods not found for %s" % obj)

    def __del__(self):
        """Saves plugin config upon ones destruction."""
        self._app.savePluginConfig(self.name, self._config)

# vim: set sts=4 sw=4 et :
